import { ElLoading, ElMessage } from 'element-plus'
import type { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'

class LoadingService {
  private loadingInstance: LoadingInstance | null = null
  private loadingCount = 0
  // @ts-ignore
  private lastMessage: string = ''

  /**
   * 显示全局loading
   */
  show(): void {
    if (this.loadingCount === 0) {
      this.loadingInstance = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: '努力加载中...',
        // background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    this.loadingCount++
  }

  /**
   * 隐藏全局loading
   */
  hide(): void {
    this.loadingCount--
    if (this.loadingCount <= 0) {
      this.loadingCount = 0
      if (this.loadingInstance) {
        this.loadingInstance.close()
        this.loadingInstance = null
      }
    }
  }

  /**
   * 显示消息提示，如果已有提示，会先关闭再显示新提示
   * @param message 消息内容
   * @param type 消息类型
   */
  showMessage(message: string, type: 'success' | 'warning' | 'info' | 'error' = 'info'): void {
    // 清除所有现有消息
    ElMessage.closeAll()
    // 更新最新消息
    this.lastMessage = message

    // 显示消息
    ElMessage({
      message,
      type,
      duration: 3000,
      showClose: true
    })
  }

  /**
   * 重置loading计数器
   */
  reset(): void {
    this.loadingCount = 0
    if (this.loadingInstance) {
      this.loadingInstance.close()
      this.loadingInstance = null
    }
  }
}

// 导出单例
export const loadingService = new LoadingService()
